/**
 * 
 */
package com.ms.game.invitefriend.db;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.ms.game.common.container.CommissionRateInfo;
import com.ms.game.common.container.LevelInfoBinUtil;
import com.ms.game.db.util.UpdateQueryBuilder;
import com.ms.game.invitefriend.bin.InviteCodeInfo;
import com.ms.game.invitefriend.bin.InviteCodeRewardBin;
import com.ms.game.invitefriend.bin.InviteCodeRewardBinUtil;
import com.ms.game.invitefriend.bin.InviteCodeType;
import com.ms.game.invitefriend.message.CGetDownLineListRequest;
import com.ms.game.invitefriend.message.ComSumInfo;
import com.ms.game.invitefriend.message.DownLineInfo;
import com.ms.game.invitefriend.message.SGetDownLineListResponse;
import com.ms.player.Player;
import com.ms.player.PlayerIdentityType;
import com.ms.player.PlayerNickNameParser;
import com.ms.service.error.ErrorCode;
import com.xpec.c4.db.dao.PlayerDAO;
import com.xpec.c4.db.hibernate.manager.HibernateLogManager;
import com.xpec.c4.db.hibernate.manager.HibernateManager;
import com.xpec.c4.db.model.PlayerModel;
import com.xpec.c4.game.common.Helper;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.game.utility.GUIDFactory;
import com.xpec.c4.game.utility.GUIDType;
import com.xpec.c4.game.utility.GameUtility;

/**
 * 邀請好友相關 DB 處理
 * 
 * @author TW15010
 */
public class InviteFriendDAO {
	private static final Log log = LogFactory.getLog(InviteFriendDAO.class);
	

	/**
	 * 取得邀請碼
	 * @param playerId
	 * @return
	 */
	public static ArrayList<InviteCodeModel> getInviteCodeModelsByPlayerId(String playerId) {
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From InviteCodeModel Where playerId = :ID and type = :TYPE1");
		query.setParameter("ID", playerId);
		query.setParameter("TYPE1", InviteCodeType.NEW_INVITE_CODE);
		ArrayList<InviteCodeModel> models = (ArrayList<InviteCodeModel>) query.list();
		HibernateManager.endSession();
		return models;
	}

	/**
	 * 加總下線在每個等級區間貢獻的總抽佣金額
	 * 
	 * @param downLineGuid
	 *            下線 guid
	 * @param lv
	 *            下線等級
	 * @param comValue
	 *            這次的抽佣金額
	 */
	public static void updateCommissionSum(CommissionRateInfo comInfo, String downLineGuid, String downLineName, String uplineId, String middleLineId, BigDecimal comValue) {
		if (downLineGuid == null) {
			return;
		}

		// 從 db 載入對應等級區間的資料
		Session session = HibernateLogManager.getSession();
		Criteria criteria = session.createCriteria(InviteFriendComSumLogModel.class);
		criteria.add(Restrictions.eq("downLineGuid", downLineGuid));
		criteria.add(Restrictions.eq("uplineId", uplineId));
		criteria.add(Restrictions.eq("rangeId", comInfo.getRangeId()));
		InviteFriendComSumLogModel model = (InviteFriendComSumLogModel) criteria.uniqueResult();
		HibernateLogManager.endSession();

		// 找不到就產生一個
		if (model == null) {
			model = new InviteFriendComSumLogModel();
			model.setDownLineGuid(downLineGuid);
			model.setRangeId(comInfo.getRangeId());
			model.setComValue(BigDecimal.ZERO);
			model.setUplineId(uplineId);
			model.setDownLineName(downLineName);
			if (middleLineId != null) {
				model.setMiddleLineId(middleLineId);
			}
		}

		// 更新數值
		model.setLvBeg(comInfo.getLvBeg());
		model.setLvEnd(comInfo.getLvEnd());

		BigDecimal newComValue = Helper.add(model.getComValue(), comValue);
		model.setComValue(newComValue);

		// 寫回 db
		try {
			session = HibernateLogManager.txBegin();
			session.saveOrUpdate(model);
			HibernateLogManager.txCommitFailRollbackClearSession();
		} catch (HibernateException e) {
			if (log.isErrorEnabled()) {
				log.error(e);
			}
		}
	}
	
	/**
	 * 經銷商邀請碼的 上線獎勵 InviteFriendComSumLogModel
	 * @return
	 */
	public static boolean insetDistributorInviteCodeDesignatedLevelComSum(byte toType, PlayerModel playerModel, DistributorInviteCodesModel inviteCodesModel, int uplineReward) {
		String guid = playerModel.getGuid();
		String name = PlayerNickNameParser.mergeNickName(playerModel);
		byte identifyType = playerModel.getPlayerIdentityType();

		Session session = HibernateLogManager.txBegin();
		
		InviteCodeInfo info = InviteCodeRewardBinUtil.getInviteCodeInfo(InviteCodeType.DISTRIBUTOR_INVITE_CODE);
		// 領取上線獎勵等級
		int designatedLevel = info.getUplineInviteRewardInfo().getDownlineNeedLevel();
		
		InviteFriendComSumLogModel model = new InviteFriendComSumLogModel();
		model.setDownLineName(name);
		model.setDownLineGuid(guid);
		model.setRangeId(0);
		model.setComValue(new BigDecimal(uplineReward));
		model.setLvBeg(designatedLevel);
		model.setLvEnd(designatedLevel);
		if (identifyType == PlayerIdentityType.SUB_DISTRIBUTOR && toType == PlayerIdentityType.DISTRIBUTOR) {
			// 子經銷商給經銷商的
			model.setUplineId(inviteCodesModel.getDistributorGuid());
		}
		
		if (identifyType == PlayerIdentityType.DOWNLINE) {
			if (toType == PlayerIdentityType.DISTRIBUTOR) {
				// 下線給經銷商
				model.setMiddleLineId(inviteCodesModel.getSubDistributorGuid());
				model.setUplineId(inviteCodesModel.getDistributorGuid());
			}

			if (toType == PlayerIdentityType.SUB_DISTRIBUTOR) {
				// 下線給子經銷商
				model.setUplineId(inviteCodesModel.getSubDistributorGuid());
			}
		}
		
		session.save(model);
		return HibernateLogManager.txCommitFailRollbackClearSession();
	}
	
	
	public static boolean insertDistributorInviteCodeDesignatedLevelCom(byte toType, PlayerModel playerModel, DistributorInviteCodesModel inviteCodesModel, int uplineReward){
		InviteFriendComLogModel comModel = new InviteFriendComLogModel();
		comModel.setLv(playerModel.getLevel());
		comModel.setComValue(new BigDecimal(uplineReward));
		comModel.setGuid(playerModel.getGuid());
		comModel.setName(PlayerNickNameParser.mergeNickName(playerModel));
		comModel.setComRate(BigDecimal.ONE);
		comModel.setOrderId(GUIDFactory.createUUID(GUIDType.TYPE_COMMAND_ORDER_ID).toString());
		
		String uplineId = "",uplineName = "";
		  
		if (toType == PlayerIdentityType.DISTRIBUTOR) {
			//經銷商
			
			uplineId = inviteCodesModel.getDistributorGuid();
			
			uplineName = PlayerDAO.getPlayerNameByGuid(GUID.parseUUID(uplineId));
		}
		
		if (toType == PlayerIdentityType.SUB_DISTRIBUTOR) {
			//子經銷商
			uplineId =inviteCodesModel.getSubDistributorGuid();
			uplineName = inviteCodesModel.getSubDistributorName();
		}
		
		comModel.setUpLineGuid(uplineId);
		comModel.setUpLineName(uplineName);
		
		
		Session session = HibernateLogManager.txBegin();
		boolean result = false;
		try {
			session.save(comModel);
		}
		catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error(e);
			}
		}
		finally {
			if (session != null) {
				result = HibernateLogManager.txCommitFailRollbackClearSession();
			}
		}
		
		return result;
		
	}
	
	/**
	 * 更新使用經銷商邀請碼，InviteFriendComSumLogModel
	 * @return
	 */
	public static boolean updateDistributorInviteCodeDesignatedLevelComm(String downLineGuid, int level, String uplineId, int comValue) {
		
		Session session = HibernateLogManager.txBegin();
		UpdateQueryBuilder builder = new UpdateQueryBuilder();
		builder.setSession(session);
		builder.setTableName("InviteFriendComSumLogModel");
		builder.addSetValue("comValue",new BigDecimal(comValue));
		builder.addWhereKey("downLineGuid", downLineGuid);
		builder.addWhereKey("uplineId", uplineId);
		builder.addWhereKey("lvBeg", level);
		builder.addWhereKey("lvEnd", level);
		builder.executeQuery();
		
		return HibernateLogManager.txCommitFailRollbackClearSession();
	}
	
	
	public static boolean insertInviteFriendComSumLogModel(Player player, DistributorInviteCodesModel inviteCodesModel){
		
		String guid = player.getGuid().toString();
		String name = player.getNameWithNumber();
		byte identifyType = player.getPlayerIdentityType();
		
		InviteCodeInfo info = InviteCodeRewardBinUtil.getInviteCodeInfo(InviteCodeType.DISTRIBUTOR_INVITE_CODE);
		
		boolean success = false;
		InviteFriendComSumLogModel model = new InviteFriendComSumLogModel();
		Session session = HibernateLogManager.txBegin();
		if (identifyType == PlayerIdentityType.SUB_DISTRIBUTOR) {
			//子經銷商建立一筆經銷商的
			model.setDownLineName(name);
			model.setDownLineGuid(guid);
			model.setRangeId(0);
			model.setComValue(new BigDecimal(0));
			model.setUplineId(inviteCodesModel.getDistributorGuid());
			model.setLvBeg(info.getUplineInviteRewardInfo().getDownlineNeedLevel());
			model.setLvEnd(info.getUplineInviteRewardInfo().getDownlineNeedLevel());
			session.save(model);
		} else if (identifyType == PlayerIdentityType.DOWNLINE) {
			//下線建兩種
			//先給經銷商
			model.setDownLineName(name);
			model.setDownLineGuid(guid);
			model.setRangeId(0);
			model.setComValue(new BigDecimal(0));
			model.setUplineId(inviteCodesModel.getDistributorGuid());
			model.setMiddleLineId(inviteCodesModel.getSubDistributorGuid());
			model.setLvBeg(info.getUplineInviteRewardInfo().getDownlineNeedLevel());
			model.setLvEnd(info.getUplineInviteRewardInfo().getDownlineNeedLevel());
			session.save(model);
			session.flush();
			//再給子經銷商的
			model = new InviteFriendComSumLogModel();
			model.setDownLineName(name);
			model.setDownLineGuid(guid);
			model.setRangeId(0);
			model.setComValue(new BigDecimal(0));
			model.setUplineId(inviteCodesModel.getSubDistributorGuid());
			model.setLvBeg(10);
			model.setLvEnd(10);
			session.save(model);
		}
			
		success =  HibernateLogManager.txCommitFailRollbackClearSession();
		return success;
	}

	/**
	 * 取得指定角色的下線清單
	 * 
	 * @param playerGuid
	 *            角色 guid
	 * @param request
	 *            取得清單的相關參數
	 * @return 可以直接傳給 client 的結果
	 */
	public static SGetDownLineListResponse getDownLineList(GUID playerId, CGetDownLineListRequest request) {
		SGetDownLineListResponse response = new SGetDownLineListResponse();

		// 參數檢查
		if (playerId == null || request == null) {
			response.setResultCode(ErrorCode.INVALID_PARAM);
			return response;
		}

		// 計算頁數、取資料的起始位置
		int pageNum = request.getPageNum();
		if (pageNum < 1) {
			pageNum = 1;
		}

		int maxPerPage = request.getItemCountPerPage();
		int beginPos = (pageNum - 1) * maxPerPage;

		Player player = PlayerDAO.loadPlayerByGuid(playerId);
		
		// 取得下線角色清單總數量
		Session session = HibernateManager.getSession();
		Query query;
		
		String queryString = "";
		if (pageNum == 1){			
			queryString= "select count(p) from PlayerModel p , InviteCodeModel i where p.uplineCode = i.inviteCode and p.uplineId = :ID and i.type = :TYPE and p.canMakeCommission = true ";

			query = session.createQuery(queryString);
			query.setParameter("ID", playerId.toString());
			query.setParameter("TYPE", InviteCodeType.DISTRIBUTOR_INVITE_CODE);
			long dataCount = (long) query.uniqueResult();
			response.setMaxPage(GameUtility.calculatePageCount((int)dataCount, maxPerPage));
		}

		queryString= "select p from PlayerModel p , InviteCodeModel i where p.uplineCode = i.inviteCode and p.uplineId = :ID and i.type = :TYPE and p.canMakeCommission = true ";
		query = session.createQuery(queryString);
		query.setParameter("ID", playerId.toString());
		query.setParameter("TYPE", InviteCodeType.DISTRIBUTOR_INVITE_CODE);
		query.setFirstResult(beginPos);
		query.setMaxResults(maxPerPage);
		ArrayList<PlayerModel> downLineModelList = (ArrayList<PlayerModel>) query.list();
		
		HibernateManager.endSession();
		
		// 填入下線清單
		ArrayList<DownLineInfo> infoList = new ArrayList<DownLineInfo>();
		session = HibernateLogManager.getSession();
		for (PlayerModel downLineModel : downLineModelList) {
			
			DownLineInfo info = new DownLineInfo();
			info.setDownLineGuid(downLineModel.getGuid());
			info.setFacephoto(downLineModel.getFacephoto());
			info.setName(downLineModel.getName());
			info.setLevel(downLineModel.getLevel());
			info.setGold(String.valueOf(downLineModel.getGoldCoin()));
			
			InviteCodeType type = InviteFriendDAO.getInviteCodeType(downLineModel.getUplineCode());
			info.setComRate(String.valueOf(LevelInfoBinUtil.getCommissionRate(downLineModel.getLevel(),type)));

			// 計算總抽佣金額
			query = session
					.createQuery("select sum(comValue) from InviteFriendComSumLogModel where downLineGuid = :downLineGuid group by downLineGuid");
			query.setParameter("downLineGuid", downLineModel.getGuid());
			BigDecimal sum = (BigDecimal) query.uniqueResult();
			if (sum == null) {
				info.setComValue("0");
			} else {
				info.setComValue(String.valueOf(sum.doubleValue()));
			}

			infoList.add(info);
		}
		HibernateLogManager.endSession();
		response.setDownLineList(infoList);

		response.setResultCode(ErrorCode.SUCCESS);
		return response;
	}

	/**
	 * 載入角色各等級範圍內抽佣金額加總資料
	 * 
	 * @param playerGuid
	 *            player guid
	 * @return 簡化的消息用格式
	 */
	public static ArrayList<ComSumInfo> loadCommissionSumList(GUID playerGuid) {
		ArrayList<ComSumInfo> comSumList = new ArrayList<ComSumInfo>();

		if (playerGuid == null) {
			return comSumList;
		}

		// 載入角色的抽佣金額加總資料
		Session session = HibernateLogManager.getSession();

		Query query = session.createQuery("from InviteFriendComSumLogModel where downLineGuid = :downLineGuid");
		query.setParameter("downLineGuid", playerGuid.toString());

		@SuppressWarnings("unchecked")
		ArrayList<InviteFriendComSumLogModel> modelList = (ArrayList<InviteFriendComSumLogModel>) query.list();

		HibernateLogManager.endSession();

		// 轉成消息用格式
		for (InviteFriendComSumLogModel model : modelList) {
			ComSumInfo info = new ComSumInfo();

			info.setRangeId(model.getRangeId());
			info.setComSum(String.valueOf(model.getComValue().doubleValue()));

			comSumList.add(info);
		}

		return comSumList;
	}
	
	public static Long checkInviteCodeExpiration(InviteCodeType type , String inviteCode){
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("select expiration from InviteCodeModel where type = :type and inviteCode = :inviteCode");
		query.setParameter("type", type);
		query.setParameter("inviteCode", inviteCode);
		Long expiration = (Long)query.uniqueResult();
		HibernateManager.endSession();
		return expiration;
	}
	
	public static InviteCodeModel loadInviteCodeModelFromInviteCode(InviteCodeType type , String inviteCode){
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From InviteCodeModel where type = :TYPE and inviteCode = :INVITECODE");
		query.setParameter("TYPE", type);
		query.setParameter("INVITECODE", inviteCode);
		InviteCodeModel model = (InviteCodeModel) query.uniqueResult();
		HibernateManager.endSession();
		return model;
	}
	
	public static boolean markUsedInviteCode(InviteCodeType type , String inviteCode){
		Session session = HibernateManager.txBegin();
		Query query = session.createQuery("update  InviteCodeModel set haveBeenUsed = true where type = :type and inviteCode = :inviteCode");
		query.setParameter("type", type);
		query.setParameter("inviteCode", inviteCode);
		query.executeUpdate();
		return HibernateManager.txCommitFailRollbackClearSession();
	}
	
	/**
	 * 找出所有使用過邀請碼的下線
	 */
	public static ArrayList<HashMap<String,String>> getUsedInviteCodePlayers(String playerId){
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("select guid,uplineCode from PlayerModel where uplineId =:playerId)");
		query.setParameter("playerId", playerId);
		ArrayList<HashMap<String,String>> models = (ArrayList<HashMap<String,String>>)query.list();
		HibernateManager.endSession();
		
		return models;
	}
	
	public static InviteCodeModel getInviteCodeModel(String uplineCode){
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From InviteCodeModel Where inviteCode = :CODE");
		query.setParameter("CODE", uplineCode);
		InviteCodeModel model = (InviteCodeModel)query.uniqueResult();
		HibernateManager.endSession();
		return model;
	}
	
	
	public static InviteCodeType getInviteCodeType(String uplineCode) {
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From InviteCodeModel Where inviteCode = :CODE");
		query.setParameter("CODE", uplineCode);
		InviteCodeModel model = (InviteCodeModel)query.uniqueResult();
		HibernateManager.endSession();
		
		if(model == null){
			return null;
		}

		InviteCodeType inviteCodeType = model.getType();
		
		if(inviteCodeType == null){
			return null;
		}
		
		InviteCodeInfo inviteCodeInfo = InviteCodeRewardBin.getInstance().getInviteCodeInfoMap().get(inviteCodeType);
		if(inviteCodeInfo == null){
			return null;
		}
		
		if(model.getInviteCode().length() != inviteCodeInfo.getCodeLength()){
			return null;
		}
		
		return inviteCodeType;
	}
	
	public static int getInviteCodeUsedNum(String inviteCode) {
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("Select count(*) from PlayerModel where uplineCode = :CODE");
		query.setParameter("CODE", inviteCode);
		Long count = (Long) query.uniqueResult();
		HibernateManager.endSession();
		return count.intValue();
	}
	
	
	/**
	 * 產出 新制邀請碼 
	 * count 是要幾組
	 * @param uplineId
	 * @param count
	 * @return
	 */
	public synchronized static boolean createNewInviteCode(String playerId, int count, InviteCodeType type, Integer upperLimit) {
		Session session =HibernateManager.getSession();	
		//因為效能差不多，為了好看所以從後面取三筆
		Query query = session.createQuery("From PreparedInviteCodeModel order by id desc");
		query.setFirstResult(0);
		query.setMaxResults(count);
		ArrayList<PreparedInviteCodeModel> preInviteCodes = (ArrayList<PreparedInviteCodeModel>) query.list();
		HibernateManager.endSession();
		
		ArrayList<Integer> ids = new ArrayList<Integer>();
		
		boolean isSingleUse = InviteCodeRewardBinUtil.getInviteCodeInfo(type).isSingleUse();
		int limit = (isSingleUse) ? 1 : upperLimit.intValue();
		
		session = HibernateManager.txBegin();
		for(int num = 0 ; num <count ; num++){
			PreparedInviteCodeModel preModel = preInviteCodes.get(num);
			InviteCodeModel model = new InviteCodeModel();
			model.setType(type);
			model.setPlayerId(playerId);
			model.setInviteCode(preModel.getInviteCode());
			model.setExpiration(0);
			model.setSingleUse(isSingleUse);
			model.setNotes(type.getNotes());
			model.setUpperLimit(limit);
			session.save(model);
			
			ids.add(preModel.getId());
		}
		
		query = session.createQuery("Delete From PreparedInviteCodeModel where id in :IDS");
		query.setParameterList("IDS", ids);
		query.executeUpdate();
		
		if(!HibernateManager.txCommitFailRollbackClearSession()){
			if (log.isErrorEnabled()) {
				log.error(GameUtility.getCurMethodName() + "txCommitFail ", new RuntimeException());
			}
			return false;
		}
		return true;
	}
	
	/**
	 * 建立邀請碼群組
	 * @return
	 */
	public static InviteCodeGroupModel createInviteCodeGroup(InviteCodeType type, String groupName, int totalCount, String goldCoins, String items, Date endTime){
		InviteCodeGroupModel groupModel = new InviteCodeGroupModel();
		groupModel.setType(type);
		groupModel.setGroupName(groupName);
		groupModel.setTotalCount(totalCount);
		groupModel.setGoldCoins(goldCoins);
		groupModel.setItems(items);
		groupModel.setEndTime(endTime);
		
		Session session = HibernateManager.txBegin();
		session.save(groupModel);
		boolean success = HibernateManager.txCommitFailRollbackClearSession();
		return success ? groupModel : null;
	}
	
	public static InviteCodeGroupModel getInviteCodeGroupModelById(String groupId){
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From InviteCodeGroupModel Where groupId = :ID");
		query.setParameter("ID", groupId);
		InviteCodeGroupModel model = (InviteCodeGroupModel)query.uniqueResult();
		HibernateManager.endSession();
		return model;
	}
	
	public static boolean createInviteCodeUseRecord(Player player, InviteCodeModel inviteCodeModel, DistributorInviteCodesModel distributorInviteCodesModel, String openId, long goldCoin, String item) {
		
		InviteCodeUseRecordModel model = new InviteCodeUseRecordModel();
		model.setAccountId(player.getAccountId().toString());
		model.setGuid(player.getGuid().toString());
		model.setInviteCode(player.getUplineCode());
		model.setGoldCoin(goldCoin);
		model.setItmes(item);
		model.setPlayerName(player.getNameWithNumber());
		model.setOpenId(openId);
		
		if(inviteCodeModel != null){
			model.setType(inviteCodeModel.getType());
			model.setGroupId(inviteCodeModel.getGroupId());
		} else if(distributorInviteCodesModel != null){
			model.setType(InviteCodeType.DISTRIBUTOR_INVITE_CODE);
		}
		
		Session session = HibernateLogManager.txBegin();
		session.save(model);
		return HibernateLogManager.txCommitFailRollbackClearSession();
	}
	
	public static boolean updateInviteCodeGroupModel(InviteCodeGroupModel inviteCodeGroupModel){
		Session session = HibernateManager.txBegin();
		session.update(inviteCodeGroupModel);
		return HibernateManager.txCommitFailRollbackClearSession();
	}
	
	/**
	 * 修改群組邀請碼，用在改群組邀請碼資訊的時候
	 * @param groupModel
	 * @return
	 */
	public static boolean modifyGroupInviteCodesInfo(InviteCodeGroupModel groupModel) {
		if(groupModel.getType() == null && groupModel.getGroupName() == null && groupModel.getEndTime() == null){
			return true;
		}
		
		Session session = HibernateManager.txBegin();
		UpdateQueryBuilder builder = new UpdateQueryBuilder();
		builder.setSession(session);
		builder.addWhereKey("groupId", groupModel.getGroupId());
		builder.setTableName("InviteCodeModel");
		
		if(groupModel.getType() != null){
			builder.addSetValue("type", groupModel.getType());
		}
		
		if(groupModel.getGroupName() != null){
			builder.addSetValue("notes", groupModel.getGroupName());
		}
		
		if(groupModel.getEndTime() != null) {
			builder.addSetValue("expiration", groupModel.getEndTime().getTime());
		}
		
		
		builder.executeQuery();
		return HibernateManager.txCommitFailRollbackClearSession();
	}
	
	public static boolean invalidGroupInviteCode(String groupId, int start, int end ,boolean invalid) {
		Session session = HibernateManager.txBegin();
		Query query = session.createQuery("Update InviteCodeModel set invalid = :INVALID Where groupId = :ID and snInGroup between :START and :END");
		query.setBoolean("INVALID", invalid);
		query.setParameter("ID", groupId);
		query.setParameter("START", start);
		query.setParameter("END", end);
		query.executeUpdate();
		return HibernateManager.txCommitFailRollbackClearSession();
	}
	
}
